<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realm API</title>
</head>
<body>
    <h1>Realm API</h1>
    <h2>提供一个全新的全局对象</h2>

    <script>
        // Realm API提案的用法
        /*
        const realm = new Realm();
        const globalObj = realm.global;
        globalObj.Array === Array; // false
        */

        // 模拟Realm的实现
        class MockRealm {
            constructor() {
                this.iframe = document.createElement('iframe');
                document.body.appendChild(this.iframe);
                this.global = this.iframe.contentWindow;
            }

            evaluate(code) {
                return this.global.eval(code);
            }

            destroy() {
                document.body.removeChild(this.iframe);
            }
        }

        // 实际应用示例
        // 1. 安全的代码执行环境
        const sandbox = new MockRealm();
        try {
            sandbox.evaluate(`
                const result = [1, 2, 3].map(x => x * 2);
                console.log(result);
            `);
        } finally {
            sandbox.destroy();
        }

        // 2. 多版本库共存
        function createLibraryRealm(version) {
            const realm = new MockRealm();
            realm.evaluate(`
                // 加载特定版本的库
                const library = loadLibrary('${version}');
            `);
            return realm;
        }

        // 3. 测试环境隔离
        class TestEnvironment {
            constructor() {
                this.realm = new MockRealm();
            }

            async runTest(testCode) {
                try {
                    // 在隔离环境中运行测试
                    await this.realm.evaluate(`
                        ${testCode}
                        runTests();
                    `);
                } finally {
                    this.cleanup();
                }
            }

            cleanup() {
                this.realm.destroy();
            }
        }

        // 4. 模块加载器
        class ModuleLoader {
            constructor() {
                this.realms = new Map();
            }

            async loadModule(name, version) {
                const key = `${name}@${version}`;
                if (!this.realms.has(key)) {
                    const realm = new MockRealm();
                    await realm.evaluate(`
                        import('${name}').then(module => {
                            window.moduleExports = module;
                        });
                    `);
                    this.realms.set(key, realm);
                }
                return this.realms.get(key);
            }
        }
    </script>
</body>
</html> 